package cn.com.wxd.service.rss;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.service.rss.entity.WebsiteRSSEntity;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.GlobalConstant;
import cn.com.wxd.common.data.KVMap;
import cn.com.wxd.common.framedata.FrameDataUtil;

/**
 * Title:网站RSS服务类
 * Description:cn.com.wxd.service.other.rss
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-9-7 上午10:51:55
 *
 * @author WangXuDong
 * @version 1.0
 */
public class WebsiteRSS {
    private static final Logger log = LoggerFactory.getLogger(WebsiteRSS.class);
    private static Document document = null;
    private static WebsiteRSS websiteRss;
    private static List<WebsiteRSSEntity> rssEntitys;

    private WebsiteRSS() {
    }

    /**
     * 获取实例
     *
     * @return
     */
    public static WebsiteRSS instance() {
        if (websiteRss == null) {
            websiteRss = new WebsiteRSS();
            websiteRss.init();
            return websiteRss;
        }
        if (document == null || rssEntitys == null || rssEntitys.size() <= 0) {
            websiteRss.init();
        }
        return websiteRss;
    }

    /**
     * 初始化
     * 一般在手动修改xml文件后执行次方法
     */
    public void init() {
        try {
            SAXReader reader = new SAXReader();
            reader.setEncoding("UTF-8");
            String defaultXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss><list></list></rss>";
            Element rootelement = DocumentHelper.parseText(defaultXml).getRootElement();
            //从数据库中获取数据
            String data = FrameDataUtil.getDataByName(GlobalConstant.WEBSITERSSDATANAME);
            if (data == null || data.trim().equals("")) {
                savaData(rootelement);
                data = defaultXml;
            }
            document = reader.read(new ByteArrayInputStream(data.getBytes("UTF-8")));
        } catch (DocumentException e) {
            log.error("读取rss列表文件错误！", e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        rssEntitys = new ArrayList<>();
        Element root = document.getRootElement();
        //获取list节点
        Element elelist = root.element("list");
        List nodes = elelist.elements("item");
        for (Iterator it = nodes.iterator(); it.hasNext(); ) {
            Element elm = (Element) it.next();
            WebsiteRSSEntity fe = new WebsiteRSSEntity();
            Element ename = elm.element("name");
            Element eurl = elm.element("url");
            Element edescription = elm.element("description");
            Element etimestamp = elm.element("timestamp");
            if (ename != null && ename.getText() != null) {
                fe.setName(ename.getText());
            } else {
                fe.setName("");
            }
            if (eurl != null && eurl.getText() != null) {
                fe.setUrl(eurl.getText());
            } else {
                fe.setUrl("");
            }
            if (edescription != null && edescription.getText() != null) {
                fe.setDescription(edescription.getText());
            } else {
                fe.setDescription("");
            }
            if (etimestamp != null && etimestamp.getText() != null) {
                fe.setTimeStamp(etimestamp.getText());
            } else {
                fe.setTimeStamp("");
            }
            rssEntitys.add(fe);
        }
    }

    /**
     * 获取保存的Rss列表
     *
     * @return
     */
    public List<WebsiteRSSEntity> getRssList() {
        return rssEntitys;
    }

    /**
     * 添加RSS
     *
     * @param fle
     *
     * @throws IOException
     */
    public void addRss(WebsiteRSSEntity wre) {
        //创建根节点
        if (wre == null) {
            return;
        }
        if (wre.getName() == null) {
            wre.setName("");
        }
        if (wre.getUrl() == null) {
            wre.setUrl("");
        }
        if (wre.getDescription() == null) {
            wre.setDescription("");
        }
        if (wre.getTimeStamp() == null || wre.getTimeStamp().equals("")) {
            wre.setTimeStamp(DateUtil.getTimestamp());
        }
        Element root = document.getRootElement();
        //获取list节点
        Element elelist = root.element("list");
        Element elm = elelist.addElement("item");
        Element elmname = elm.addElement("name");
        //elmname.setText(wre.getName());
        elmname.addCDATA(wre.getName());
        Element ellink = elm.addElement("url");
        //ellink.setText(wre.getUrl());
        ellink.addCDATA(wre.getUrl());
        Element elmdescription = elm.addElement("description");
        //elmdiscript.setText(wre.getDiscript());
        elmdescription.addCDATA(wre.getDescription());
        Element elmtimestamp = elm.addElement("timestamp");
        elmtimestamp.setText(wre.getTimeStamp());
        savaData(root);
        init();
    }

    /**
     * 删除一条Rss,
     *
     * @param timeStamp 时间戳
     */
    public void deleteRss(String timeStamp) {
        if (timeStamp == null) {
            return;
        }
        //创建根节点
        Element root = document.getRootElement();
        //获取list节点
        Element elelist = root.element("list");
        List<Element> nodes = elelist.elements("item");
        for (Iterator<Element> it = nodes.iterator(); it.hasNext(); ) {
            Element elm = it.next();
            Element etimestamp = elm.element("timestamp");
            if (etimestamp != null && etimestamp.getText().equalsIgnoreCase(timeStamp)) {
                elelist.remove(elm);
            }
        }
        savaData(root);
        init();
    }

    /**
     * 修改Rss
     *
     * @param timeStamp 时间戳
     * @param param     key是节点 value是值
     */
    public void editRss(String timeStamp, KVMap<String, String> param) {
        if (timeStamp == null) {
            return;
        }
        //创建根节点
        Element root = document.getRootElement();
        //获取list节点
        Element elelist = root.element("list");
        List<Element> nodes = elelist.elements("item");
        for (Iterator<Element> it = nodes.iterator(); it.hasNext(); ) {
            Element elm = it.next();
            Element etimestamp = elm.element("timestamp");
            if (etimestamp != null && etimestamp.getText().equalsIgnoreCase(timeStamp)) {
                if (param != null) {
                    List<Element> allnodes = elm.elements();
                    for (Iterator<Element> allit = allnodes.iterator(); allit.hasNext(); ) {
                        Element allele = allit.next();
                        String nodeName = allele.getName();
                        for (int j = 0; j < param.size(); j++) {
                            if (param.getKeyIndex(j).equalsIgnoreCase(nodeName)) {
                                allele.setText(param.getValueIndex(j));
                            }
                        }
                    }
                }
            }
        }
        savaData(root);
        init();
    }

    /**
     * 保存数据
     *
     * @param _document
     */
    private static void savaData(Element _document) {
        String data = _document.asXML();
        try {
            FrameDataUtil.saveFrameData(GlobalConstant.WEBSITERSSDATANAME, data);
        } catch (Exception e) {
            log.error("", e);
        }
    }
}
